/**
 * @Author: Nico
 */
import { gp } from '@vui'
import isEmpty from 'lodash/isEmpty'
import cloneDeep from 'lodash/cloneDeep'
import isArray from 'lodash/isArray'
import merge from 'lodash/merge'
import isPlainObject from 'lodash/isPlainObject'
import { getModelInfo } from '@ve/utils/getModelInfo'
// import { decryptd } from '@/utils/tools'
import request from '@/utils/request'
import { GFCD } from '@/utils/utils'
import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
import { ElMessage } from 'element-plus'
import pdaInjectData from './logic/pdaInjectData'
import { translateTitle } from '@/utils/i18n'
// import { Toast } from 'vant'

// let requestOpen = false
//必须带done回调 执行完成调用\
export default function pdaRequestApi({ vm, action, callbackData, done, eventName }) {
  console.log('pda调用接口1', callbackData, action)
  let { type, useCallbackData, api, method, getDataKey, data, openMessage } = action.extension.requestConfig.value
  const InjectGetDataKey = action.extension.receiveObject && action.extension.receiveObject.value && action.extension.receiveObject.value.source
  let _additionalData = {} //附加数据 比如来自组件的自定义参数
  let _data = {}
  let _modelInfo = {}
  let _selfRef = null
  // type=1 以自己配置为主
  if (type == 1) {
    data.forEach((v) => {
      console.log('isPlainObject', isPlainObject(v.value), v)
      if (isPlainObject(v.value)) {
        let _value = ''
        const moduleId = v.value.sourceId.value.source[0] || ''
        // 如果参数值是对象的话 则代表是复杂参数 则需要找到对应模块取值
        if (!moduleId) return
        const formItem = vm.vuiComponents[moduleId] //获取选中得组件
        console.log('formItem===', formItem)
        const _formModule = formItem.self.formId && vm.vuiComponents[formItem.self.formId].self
        const _formModel = formItem.self.info.extension.model && formItem.self.info.extension.model.value
        if (_formModule && _formModel) {
          _value = _formModule.info.data.formData[_formModel]
          // console.log('pda调用接口2', _value)
        } else {
          _value = formItem.self.formDataModel
        }
        //
        // 通过这个 moduleId ，在vm.vuiComponents里面拿到组件实例（self）

        if (v.key == 'PdaBatch') {
          // 在这里直接调用PDA批次组件的 getLotValue 方法即可获取批次属性的值
          const LotValue = formItem.self && formItem.self.getLotValue()
          // 在这里可以选择直接把这48个值合并到参数对象或者是封装前面的Key
          _data = { ..._data, ...LotValue }
        } else {
          _data[v.key] = processingConstant(vm, _value)
        }
      } else {
        // 给输入框设置死得值
        _data[v.key] = processingConstant(vm, v.value)
        // }
      }
    })
    // 回调数据
    if (useCallbackData && !isEmpty(callbackData)) {
      if (isArray(callbackData)) {
        _data = callbackData.map((item) => {
          // 解析配置参数的变量
          data.forEach((v) => {
            let itemVal = v.value
            if (/{[^#{]+}/g.test(v.value)) {
              // itemVal = item[trim(v.value.substring(2, v.value.length - 1))]
              itemVal = replaseRegVariable(itemVal, item)
            }
            if (!isPlainObject(itemVal)) {
              _data[v.key] = processingConstant(vm, itemVal)
            }
          })
          return merge(item, _data)
        })
      } else {
        // 解析配置参数的变量
        data.forEach((v) => {
          let itemVal = v.value
          if (/{[^#{]+}/g.test(v.value)) {
            itemVal = replaseRegVariable(itemVal, callbackData)
          }
          if (isPlainObject(itemVal)) {
            let _value = ''
            const moduleId = v.value.sourceId.value.source[0] || ''
            if (!moduleId) return
            const formItem = vm.vuiComponents[moduleId] //获取选中得组件
            _value = formItem.self.formDataModel
            _data[v.key] = processingConstant(vm, _value)
          } else {
            if (/#{.*?}/g.test(v.value)) {
              // 变量解析
              _data[v.key] = processingConstant(vm, replaseRegVariable(v.value, callbackData))
            } else {
              // 给输入框设置死得值
              _data[v.key] = processingConstant(vm, v.value)
            }
          }
        })
        _data = {
          ...cloneDeep(callbackData),
          ..._data,
        }
      }
      // } else {
      //   _data = { ..._data, ...callbackData }
      // }
    }
  }
  //type=2 以组件配置为主
  if (type == 2) {
    //通过组件id找到模块信息
    let _componentId = action.extension.requestConfig.value.component[0]
    if (!_componentId) {
      ElMessage({
        showClose: true,
        message: translateTitle('pda.elements.调用接口请选择需要调用接口的组件'),
        type: 'error',
      })
    }
    _modelInfo = getModelInfo(vm, _componentId)
    if (_modelInfo.type == 'uiPdaUpload') {
      _selfRef = vm.vuiComponents && vm.vuiComponents[_modelInfo._id]
      // 若是未选择图片，则是直接done
      if (_selfRef.self.fileList.length == 0) {
        console.log('没有选图片')
        done(null, {})
        return
      } else {
        // 选择图片之后，调用上传接口之后再done
        _selfRef.self.uploader((res) => {
          console.log('上传成功', res)
          done(null, res)
        })
        return
      }
    }

    if (['uiTable', 'uiCirculationForm', 'uiDynamicForm', 'uiDynamicFormLot', 'uiPdaBatch'].includes(_modelInfo.type)) {
      _selfRef = vm.vuiComponents && vm.vuiComponents[_modelInfo._id]
      if (_selfRef) {
        _selfRef.self.$data.loading = true
        _additionalData = _selfRef.self.$getRequestData()
      }
    }
    //中途删除组件后需要重新选择
    if (_componentId.length <= 0 || isEmpty(_modelInfo)) {
      // gp.$baseMessage('没有找到模块-requestApi', 'warning')
      console.log('没有找到模块-requestApi=========')
      vm[`${eventName}IsRunning`] = false
      return
    }

    //获取模块配置接口信息
    if (!_modelInfo.extension.api) {
      ElMessage({
        showClose: true,
        message: translateTitle('pda.elements.调用接口选择的组件未配置接口'),
        type: 'error',
      })
    }
    // console.log('Nico检查批次', _modelInfo.extension)
    api = _modelInfo.extension.api.value
    method = _modelInfo.extension.method.value
    getDataKey = _modelInfo.extension.getDataKey ? _modelInfo.extension.getDataKey.value : ''

    if (_modelInfo.type == 'uiCirculationForm' || _modelInfo.type == 'uiPdaBatch') {
      _additionalData = $getRequestData(vm, _modelInfo.extension.requestData)
    }
    if (String(_modelInfo.type).indexOf('uiDynamicForm') !== -1) {
      for (let key in _additionalData) {
        !_modelInfo.data.formData[key] && (_modelInfo.data.formData[key] = _additionalData[key])
      }
    }
    _data = {
      ..._modelInfo.data.formData,
      ..._additionalData,
      // ..._data_obj,
      ...{ '#LIMIT#': 1 },
    }
    //二次请求默认到一页
    _modelInfo.data.formData = _data
  }
  //发起请求
  request({
    url: GFCD('dams', 'domain') + api,
    method: 'post',
    data: {
      data: JSON.stringify(_data),
      method: method,
    },
    notOpenMessage: !openMessage,
  })
    .then((res) => {
      //解密
      if (type === 2) {
        if (_modelInfo.type == 'uiTable' && _selfRef) {
          _selfRef.self.$data.loading = false
        }
        _modelInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
      } else {
        if (openMessage && res.msg) {
          gp.$baseMessage(res.msg, res.code == '00000' ? 'success' : 'error')
        }
      }
      // requestOpen = false
      // let getNowPageData = vm.$store.getters['preview/getNowPageData']
      // getNowPageData.data = res
      if (!isEmpty(InjectGetDataKey)) {
        pdaInjectData({
          vm: vm,
          action: action,
          callbackData: res,
        })
      }
      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: res,
      })

      done(null, res)
    })
    .catch((error) => {
      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: error,
      })
      done(null, error)
    })
}
function $getRequestData(vm, data) {
  let _data = {}
  if (data && isArray(data.value)) {
    data.value.forEach((item) => {
      _data[item.key] = processingConstant(vm, item.value)
    })
  }
  return _data
}
